package com.dqp.cslggroup.School;

import android.annotation.SuppressLint;
import android.app.Dialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import androidx.appcompat.widget.Toolbar;
import androidx.cardview.widget.CardView;

import com.dqp.cslggroup.ConnectSever.Accept;
import com.dqp.cslggroup.ConnectSever.Send;
import com.dqp.cslggroup.EventBus.MessageEvent;
import com.dqp.cslggroup.R;
import com.dqp.cslggroup.UI.BaseActivity;
import com.dqp.cslggroup.UI.ClubMoreAdapter;
import com.dqp.cslggroup.UI.MyApplication;
import com.dqp.cslggroup.UI.MyImageLoader;
import com.dqp.cslggroup.Util.Comment;
import com.dqp.cslggroup.Util.NetCheckUtil;
import com.dqp.cslggroup.Util.ToastUtil;
import com.dqp.cslggroup.bean.student;
import com.youth.banner.Banner;
import com.youth.banner.BannerConfig;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

public class Club_more extends BaseActivity {
    private Handler handler;
    private String[] strings;
    private int[] ints;
    private ArrayList<Comment> dataList;
    private TextView fine, bad, comment;
    private ListView listView;
    private Comment comments = new Comment();
    private Banner banner;
    private ArrayList<String> list_path = new ArrayList<>();
    private LinearLayout head;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.club_more);
        EventBus.getDefault().register(this);
        Toolbar toolbar = findViewById(R.id.include_toolbar);
        toolbar.setTitle("");
        setSupportActionBar(toolbar);
        Objects.requireNonNull(getSupportActionBar()).setDisplayHomeAsUpEnabled(true);
        Intent intent = getIntent();
        strings = intent.getStringArrayExtra("string");
        String[] show = intent.getStringArrayExtra("show");
        ints = intent.getIntArrayExtra("int");
        boolean view = intent.getBooleanExtra("view", false);
        head=findViewById(R.id.list_head);
        if (view) {
            LinearLayout linearLayout = findViewById(R.id.club_hd);
            linearLayout.setVisibility(View.GONE);
            TextView web=findViewById(R.id.xy_web);
            web.setVisibility(View.VISIBLE);
            CardView cardView=findViewById(R.id.club_more_cv);
            cardView.setOnClickListener(v ->{
                Uri uri = Uri.parse(strings[4]);
                Intent intents = new Intent(Intent.ACTION_VIEW, uri);
                startActivity(intents);
            });
        }
        initCard();
        assert show != null;
        list_path.add(show[0]);
        list_path.add(show[1]);
        list_path.add(show[2]);
        startBanner(list_path);
        if (NetCheckUtil.checkNet(Club_more.this)) {
            if (!view) initCommentList();
            if (view) initProfessionList();
        }else {
            head.setVisibility(View.GONE);
            ToastUtil.showToast("请连接网络！");
        }
    }

    @SuppressLint({"SetTextI18n", "HandlerLeak"})
    public void initCard() {
        banner = findViewById(R.id.club_more_banner);
        TextView name = findViewById(R.id.club_name);
        TextView level = findViewById(R.id.club_level);
        TextView des = findViewById(R.id.club_des);
        fine = findViewById(R.id.club_fine);
        bad = findViewById(R.id.club_bad);
        comment = findViewById(R.id.club_comment);
        LinearLayout fine_lin = findViewById(R.id.club_fine_lin);
        LinearLayout bad_lin = findViewById(R.id.club_bad_lin);
        LinearLayout comment_lin = findViewById(R.id.club_comment_lin);
        if (strings.length >= 4) {
            name.setText(strings[0]);
            level.setText(strings[1]);
            des.setText(strings[2]);
            des.setVisibility(View.VISIBLE);
        }
        if (ints.length >= 3) {
            fine.setText(ints[0] + "");
            bad.setText(ints[1] + "");
            comment.setText(ints[2] + "");
        }
        fine_lin.setOnClickListener(v -> new Thread(() -> {

            if (frist_use(0)) {
                if (Send.clubEvaluation(strings[0], "fine")) {
                    EventBus.getDefault().post(new MessageEvent("Club_more", 2, null));

                } else {
                    EventBus.getDefault().post(new MessageEvent("Club_more", 5, 1));
                }
            }
        }).start());

        bad_lin.setOnClickListener(v -> new Thread(() -> {
            if (frist_use(1)) {
                if (Send.clubEvaluation(strings[0], "bad")) {
                    EventBus.getDefault().post(new MessageEvent("Club_more", 3, null));

                } else {
                    EventBus.getDefault().post(new MessageEvent("Club_more", 5, 2));
                }
            }
        }).start());
        comment_lin.setOnClickListener(v -> comment());
    }

    public void comment() {
        if (student()) {
            final android.app.AlertDialog.Builder builder = new android.app.AlertDialog.Builder(Club_more.this);
            @SuppressLint("InflateParams") View view = LayoutInflater.from(Club_more.this).inflate(R.layout.comment_edit, null);
            builder.setView(view);
            final EditText content = view.findViewById(R.id.comment_editview);
            TextView put = view.findViewById(R.id.comment_editBtn);
            Dialog dialog = builder.show();
            put.setOnClickListener(view1 -> {
                String contents = content.getText().toString();
                if (contents.length() > 1) {
                    comments.setContent(contents);
                    new Thread(() -> {
                        if (frist_use(2)) {
                            if (Send.putComment(comments, strings[0])) {
                                dialog.dismiss();
                                EventBus.getDefault().post(new MessageEvent("Club_more", 4, null));
                            } else {
                                EventBus.getDefault().post(new MessageEvent("Club_more", 5, 3));
                            }
                        } else ToastUtil.showToast("每人一天只可点赞评论一次！");
                    }).start();
                } else ToastUtil.showToast("随便说点啥吧！");
            });
        } else ToastUtil.showToast("登陆后才可评论！");
    }


    @SuppressLint({"SetTextI18n", "HandlerLeak"})
    private void initCommentList() {
        new Thread(() -> {
            ArrayList<Comment> dataList = Accept.getClubComment(strings[0]);
            EventBus.getDefault().post(new MessageEvent("Club_more", 1, dataList));
        }).start();
    }

    @SuppressLint({"SetTextI18n", "HandlerLeak"})
    private void initProfessionList() {
        new Thread(() -> {
            ArrayList<Comment> dataList = Accept.getProfession(strings[0]);
            EventBus.getDefault().post(new MessageEvent("Club_more", 1, dataList));
        }).start();
    }

    @SuppressLint("HandlerLeak")
    private boolean student() {
        List<student> studentList=MyApplication.getDaoInstant().getStudentDao().loadAll();
        if (studentList.size()>0){
            student student=studentList.get(0);
            String xh = student.getXh();
            String xm = student.getXm();
            String xb = student.getXb();
            String xy = student.getXy();
            comments.setComment_name(xm);
            comments.setCollege(xy);
            comments.setGender(xb);
            comments.setSno(xh);
            return true;
        }
        return false;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == android.R.id.home) {
            finish();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    private void startBanner(List imageUrl) {
        banner.setBannerStyle(BannerConfig.CIRCLE_INDICATOR);
        banner.setIndicatorGravity(BannerConfig.CENTER);
        MyImageLoader mMyImageLoader = new MyImageLoader();
        banner.setImageLoader(mMyImageLoader);
        banner.setImages(imageUrl);
        banner.isAutoPlay(true);
        banner.setDelayTime(3000);
        banner.start();
    }

    public boolean frist_use(int name) {
        SharedPreferences sp;
        SharedPreferences.Editor editor;
        @SuppressLint("SimpleDateFormat") SimpleDateFormat sDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        String date = sDateFormat.format(new java.util.Date());

        if (name == 0) {
            sp = getSharedPreferences("one_zan", MODE_PRIVATE);
            String isOneZan = sp.getString("one_zan", "0");
            if (!date.equals(isOneZan)) {
                editor = sp.edit();
                editor.putString("one_zan", date);
                editor.apply();
                return true;
            }
            if ("0".equals(isOneZan)) {
                editor = sp.edit();
                editor.putString("one_zan", date);
                editor.apply();
                return true;
            }
        }
        if (name == 1) {
            sp = getSharedPreferences("one_Bad", MODE_PRIVATE);
            String isOneBad = sp.getString("one_Bad", "0");
            if (!date.equals(isOneBad)) {
                editor = sp.edit();
                editor.putString("one_Bad", date);
                editor.apply();
                return true;
            }
            if ("0".equals(isOneBad)) {
                editor = sp.edit();
                editor.putString("one_Bad", date);
                editor.apply();
                return true;
            }
        }
        if (name == 2) {
            sp = getSharedPreferences("one_Comment", MODE_PRIVATE);
            String isOneComment = sp.getString("one_Comment", "0");
            if (!date.equals(isOneComment)) {
                editor = sp.edit();
                editor.putString("one_Comment", date);
                editor.apply();
                return true;
            }
            if ("0".equals(isOneComment)) {
                editor = sp.edit();
                editor.putString("one_Comment", date);
                editor.apply();
                return true;
            }
        }
        return false;

    }


    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }


    @SuppressLint("SetTextI18n")
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(MessageEvent event) {
        if (event.getEvent().equals("Club_more")) {
            switch (event.getWhat()) {
                case 1:
                    dataList = (ArrayList<Comment>) event.getObj();
                    listView = findViewById(R.id.club_more_list);
                    ClubMoreAdapter clubMoreAdapter = new ClubMoreAdapter(dataList, Club_more.this);
                    listView.setAdapter(clubMoreAdapter);
                    head.setVisibility(View.GONE);
                    break;
                case 2:
                    ints[0]++;
                    fine.setText(ints[0] + "");
                    break;
                case 3:
                    ints[1]++;
                    bad.setText(ints[1] + "");
                    break;
                case 4:
                    ints[2]++;
                    comment.setText(ints[2] + "");
                    initCommentList();
                    break;
                case 5:
                    String s = null;
                    if (event.getZhou() == 1)
                        s = "鼓励";
                    if (event.getZhou() == 2)
                        s = "吐槽";
                    if (event.getZhou() == 3)
                        s = "评论";
                    ToastUtil.showToast(s + "失败！");
                    break;
            }
        }
    }


}
